package com.lzit.smart_canteen.controller;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationOutput;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzit.smart_canteen.domain.ImageOptionsDTO;
import com.lzit.smart_canteen.dto.AIChatHistory;
import com.lzit.smart_canteen.dto.AIChatRequest;
import com.lzit.smart_canteen.service.AiService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.image.Image;
import org.springframework.ai.image.ImageResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/AI")
public class AiController {
    private final AiService aiService;

    public AiController(AiService aiService) {
        this.aiService = aiService;
    }

    @GetMapping("toIndex")
    public String toIndex() {
        return "/AI/index";
    }

    @PostMapping("/normal")
    public ResponseEntity<String> handleNormalRequest(@RequestBody AIChatRequest data) {
        try {
            System.out.println(data);
            // 从请求中获取question
            String message = data.getQuestion();
            // 处理接收到的数据
            String result = callWithMessage(message);
            // 返回成功响应
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 如果处理过程中出现异常，可以返回错误信息
            return ResponseEntity.status(500).body("An error occurred while processing the request.");
        }
    }

    @GetMapping("/stream")
    public Flux<ChatResponse> stream(String message) {
        return this.aiService.streamCompletion(message);
    }

    public static String callWithMessage(String message) throws NoApiKeyException, ApiException, InputRequiredException {
        Generation gen = new Generation();

        QwenParam params = QwenParam.builder().model("qwen1.5-7b-chat")
                .prompt(message)
                .seed(1234)
                .topP(0.8)
                .resultFormat("message")
                .maxTokens(1500)
                .temperature((float) 0.85)
                .repetitionPenalty((float) 1.0)
                .build();

        GenerationResult result = gen.call(params);
        GenerationOutput output = result.getOutput();
        List<GenerationOutput.Choice> choices = output.getChoices();
        GenerationOutput.Choice choice = choices.get(0);
        Message message1 = choice.getMessage();
        return message1.getContent();
    }

    @PostMapping("/image")
    public void image(HttpServletRequest request, HttpServletResponse response) {
        String instructions = request.getParameter("instructions");
        System.out.println(instructions);
        ImageOptionsDTO image = new ImageOptionsDTO();
        image.setInstructions(instructions);
        ImageResponse resp = this.aiService.genImage(image.getInstructions(), image);
        resp.getResults().forEach(imageGen -> {
            Image img = imageGen.getOutput();
            String imgBase64 = img.getB64Json();
//            System.out.println(imgBase64);
            String url = img.getUrl();
            try {
                response.getWriter().write(url);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            System.out.println(url);
        });
    }
}
